package com.ymtms.arrivalofgoods.service.impl;

import com.netflix.discovery.converters.Auto;
import com.ymtms.arrivalofgoods.constant.ArriveConstant;
import com.ymtms.arrivalofgoods.constant.RandomPlace;
import com.ymtms.arrivalofgoods.dao.*;
import com.ymtms.arrivalofgoods.exception.ArriveException;
import com.ymtms.arrivalofgoods.pojo.*;
import com.ymtms.arrivalofgoods.service.GoodsbillReceoptMainService;
import com.ymtms.arrivalofgoods.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class GoodsbillReceoptMainServiceImpl implements GoodsbillReceoptMainService {
    @Autowired
    private GoodsbillReceoptMainMapper goodsbillReceoptMainMapper;
    @Autowired
    private GoodsbillMasterMapper goodsbillMasterMapper;
    @Autowired
    private WaybillMapper waybillMapper;
    @Autowired
    private CustomerInformationMapper customerInformationMapper;
    @Autowired
    private DriverInformationMapper driverInformationMapper;
    @Autowired
    private CustomerReceiptInformationMapper customerReceiptInformationMapper;
    @Autowired
    private GoodsReceiptInformationMapper goodsReceiptInformationMapper;
    @Autowired
    private CheckGoodsReceiveMapper checkGoodsReceiveMapper;
    @Autowired
    private CheckGoodsCustomerMapper checkGoodsCustomerMapper;
    @Autowired
    private GoodsbillEventMapper goodsbillEventMapper;

    /**
     * Discription 添加货物回执单
     *
     * @return
     * @Param goodsBillCode    货运单编号
     * @author Administrator
     * @date 2019/10/18 12:12
     **/
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public void addReceoptMain(String goodsBillCode) {
        int masterCount = goodsbillMasterMapper.selectCountFromGoodsbillMaster(goodsBillCode);
        if (masterCount != 1) {
            throw new ArriveException("货运单号不存在或有多个");
        }

        //通过货运单唯一编号找到货运主表数据
        try {
            GoodsbillReceoptMain receipt = new GoodsbillReceoptMain();

            GoodsbillMaster goodsbillMaster = goodsbillMasterMapper.queryGoodsbillMasterByCode(goodsBillCode);
            if (goodsbillMaster.getCarryGoodsFee() != null) {
                receipt.setDispatchServiceFee(goodsbillMaster.getCarryGoodsFee());
            }
            if (goodsbillMaster.getPayMode() != null) {
                receipt.setCarriageBanlanceMode(goodsbillMaster.getPayMode());
            }

            //通过货运主表ID找到此运输数据
            Waybill waybill = waybillMapper.queryWaybillByGoodsbillPkid(goodsbillMaster.getGmid());
            //System.out.println(waybill);
            Integer driverPkid = waybill.getDriverPkid();
            if (waybill.getTotalCarriage() != null) {
                receipt.setAllCarriage(waybill.getTotalCarriage().longValue());
            }
            if (waybill.getInsurance() != null) {
                receipt.setInsurance(waybill.getInsurance().longValue());
            }
            if (waybill.getStartPlace() != null) {
                receipt.setLoadStation(waybill.getStartPlace());
            }
            if (waybill.getStartCarryTime() != null) {
                receipt.setStartCarryTime(waybill.getStartCarryTime());
            }
            //通过运输id找到客户手机号，找到客户数据
            CustomerInformation customerInformation = customerInformationMapper.queryByCustomerPhone(waybill.getReceiveGoodsCustomerMobile());
            receipt.setReceiveGoodsLinkman(customerInformation.getLinKman());
            receipt.setLinkmanMobile(customerInformation.getLinkmanMobile());
            receipt.setLinkmanPhone(customerInformation.getPhone());
            receipt.setReceiveGoodsDetailAddr(customerInformation.getAddress());

            receipt.setDriverPkid(driverPkid);
            //通过判断货运主表中的IfSettleAccounts字段是否为未结账，插入数据IfBalance
            //如果此数据为未结账  BackBillState字段为 未回执， Execute 为0未执行（有差错的），execute为1的表示已验收
            String ifSettleAccounts = goodsbillMaster.getIfSettleAccounts();
            if (ArriveConstant.unsettled.equals(ifSettleAccounts)) {
                receipt.setIfBalance(ArriveConstant.unsettled);
            } else {
                receipt.setIfBalance(ArriveConstant.settled);
            }
            receipt.setBackBillState(ArriveConstant.unreceipted);
            receipt.setExecute(0);
             //修改运单事件为已到运单
            goodsbillEventMapper.updateEventnameByGoodsBillId(goodsbillMaster.getGmid());
            //插入货物主运单未插入的部分
            GoodsbillMaster master2 = new GoodsbillMaster();
            master2.setGmid(goodsbillMaster.getGmid());
            master2.setFactDealDate(new Date());
            master2.setWriteBillPerson(RandomPlace.randomPeople());
            master2.setWriteDate(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
            //生成交货地点
            String place = RandomPlace.randomPlace();
            master2.setAcceptStation(place);
            goodsbillMasterMapper.updateByPrimaryKeySelective(master2);
            //生成货运单唯一编号
            String uuid = CommonUtils.uuid();


            receipt.setArriveTime(new Date());
            receipt.setDealGoodsStation(place);
            receipt.setGoodsRevertBillCode(uuid);
            receipt.setGoodsBillpkid(goodsbillMaster.getGmid());
            goodsbillReceoptMainMapper.insertSelective(receipt);
            //插入验收数据
            GoodsbillReceoptMain receiptByBillCode = goodsbillReceoptMainMapper.queryReceiptByBillCode(uuid);
            CheckGoodsReceive checkGoodsReceive = new CheckGoodsReceive();
            checkGoodsReceive.setGid(receiptByBillCode.getGrmid());
            checkGoodsReceive.setStatus(ArriveConstant.unchecked);
            CheckGoodsCustomer checkGoodsCustomer = new CheckGoodsCustomer();
            checkGoodsCustomer.setGid(receiptByBillCode.getGrmid());
            checkGoodsCustomer.setStatus(ArriveConstant.unchecked);
            checkGoodsReceiveMapper.insertSelective(checkGoodsReceive);
            checkGoodsCustomerMapper.insertSelective(checkGoodsCustomer);

        } catch (ArriveException e) {
            e.printStackTrace();
        }
    }

    /**
     * Discription 根据条件查询数据
     *
     * @return
     * @Param 1.条件
     * @Param 2.到达开始时间条件
     * @Param 3.到达结束时间条件
     * @author Administrator
     * @date 2019/10/19 16:01
     **/
    @Override
    public List<GoodsbillReceoptMain> findAllGoodsbillReceiptByCondition(Integer currentPage, Integer pageSize, GoodsbillReceoptMain goodsbillReceoptMain,
                                                                         Date arriveBegin, Date arriveEnd, String linkmanPhone) {

        try {
            List<GoodsbillReceoptMain> lists = goodsbillReceoptMainMapper.queryAllGoodsbillByCondition(currentPage, pageSize, goodsbillReceoptMain, arriveBegin, arriveEnd, linkmanPhone);
            for (GoodsbillReceoptMain list : lists) {
                DriverInformation driver = driverInformationMapper.selectByPrimaryKey(list.getDriverPkid());
                CheckGoodsCustomer checkGoodsCustomer = checkGoodsCustomerMapper.queryByReceiptId(list.getGrmid());
                CheckGoodsReceive checkGoodsReceive = checkGoodsReceiveMapper.queryByReceiptId(list.getGrmid());
                if (checkGoodsCustomer != null && checkGoodsReceive != null) {
                    list.setCheckGoodsCustomer(checkGoodsCustomer);
                    list.setCheckGoodsReceive(checkGoodsReceive);
                }
                if (driver != null) {
                    list.setDriverInformation(driver);
                }

                /*if (list.getDriverInformation().getDriverName()!=null)
                { System.out.println(list.getDriverInformation().getDriverName()+"-->>");}*/
            }

            return lists;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * Discription Todo根据Id查询一条数据
     *
     * @return
     * @Param
     * @author Administrator
     * @date 2019/10/21 10:19
     **/
    @Override
    public GoodsbillReceoptMain findOneReceiptById(Integer grmid) {
        return goodsbillReceoptMainMapper.selectByPrimaryKey(grmid);
    }

    /**
     * Discription Todo修改数据
     *
     * @return
     * @Param
     * @author Administrator
     * @date 2019/10/21 10:20
     **/
    @Override
    public void modifyOneReceipt(GoodsbillReceoptMain goodsbillReceoptMain) {


        if (goodsbillReceoptMain != null && goodsbillReceoptMain.getGrmid() != null) {
            if (ArriveConstant.unsettled.equals(goodsbillReceoptMain.getIfBalance())) {

                checkGoodsCustomerMapper.updateUnCheckCustomerByNum(goodsbillReceoptMain.getGrmid());
            }
        }
        goodsbillReceoptMainMapper.updateByPrimaryKeySelective(goodsbillReceoptMain);
    }


    /**
     * Discription Todo客户接收货物的处理
     *
     * @return
     * @Param
     * @author Administrator
     * @date 2019/10/21 11:03
     **/
    @Override
    public void acceptGoods(Integer grmid) {

        GoodsbillReceoptMain goodsbillReceoptMain = goodsbillReceoptMainMapper.selectByPrimaryKey(grmid);
        GoodsbillMaster goodsbillMaster = goodsbillMasterMapper.selectByPrimaryKey(goodsbillReceoptMain.getGoodsBillpkid());
        DriverInformation driverInformation = driverInformationMapper.selectByPrimaryKey(goodsbillReceoptMain.getDriverPkid());
        String ifBalance = goodsbillReceoptMain.getIfBalance();
        //已结账进行验收
        if (ArriveConstant.settled.equals(ifBalance)) {

            //插入客户回执表
            CustomerReceiptInformation customerReceiptInformation = new CustomerReceiptInformation();
            customerReceiptInformation.setGoodsBillCode(goodsbillMaster.getGoodsBillCode());
            customerReceiptInformation.setCustomer(goodsbillMaster.getSendGoodsCustomer());
            customerReceiptInformation.setCheckGoodsRecord(ArriveConstant.checked);
            customerReceiptInformation.setReceiveGoodsPerson(goodsbillReceoptMain.getLinkmanMobile());
            customerReceiptInformation.setReceiveGoodsDate(new Date());
            customerReceiptInformation.setCarryBillEventPkid(0);
            customerReceiptInformationMapper.insertSelective(customerReceiptInformation);
            //插入货物回执表
            GoodsReceiptInformation goodsReceiptInformation = new GoodsReceiptInformation();
            goodsReceiptInformation.setGoodsRevertCode(goodsbillReceoptMain.getGoodsRevertBillCode());
            goodsReceiptInformation.setDriverName(driverInformation.getDriverName());
            goodsReceiptInformation.setCheckGoodsRecord(ArriveConstant.checked);
            goodsReceiptInformation.setReceiveGoodsPerson(goodsbillReceoptMain.getReceiveGoodsLinkman());
            goodsReceiptInformation.setReceiveGoodsDate(new Date());
            goodsReceiptInformationMapper.insertSelective(goodsReceiptInformation);
        } else {
            //进行收款业务处理


        }
    }


    /**
     * Discription Todo对未验收的数据缓存处理
     *
     * @return
     * @Param
     * @author Administrator
     * @date 2019/10/23 17:46
     **/
    //@Cacheable(value = "unsettledReceipt",key = "#root.methodName")
    @Override
    public List findAllUnsettledReceipt() {
        List<GoodsbillReceoptMain> allUnsettledReceipt = goodsbillReceoptMainMapper.findAllUnsettledReceipt();
        return allUnsettledReceipt;

    }

    @Override
    public GoodsbillReceoptMain findByBillcode(String billcode) {

        return goodsbillReceoptMainMapper.queryReceiptByBillCode(billcode);

    }

    @Override
    public void updateReceiptByBillcode(String billcode) {
        goodsbillReceoptMainMapper.updateGoodsbillReceipt(billcode);
    }

    @Override
    public void deleteReceiptByKeys(Integer[] keys) {
        goodsbillReceoptMainMapper.removeBatchByKey(keys);
    }

    @Override
    public GoodsbillReceoptMain findReceiptMainByPkid(Integer gmid) {
        return goodsbillReceoptMainMapper.findReceiptMainByPkid(gmid);
    }


}









